﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test;

public static class ShaderUtil
{
    public static bool ReadShader(string path, ref string shaderCode)
    {
        if (!Path.Exists(path))
        {
            throw new FileNotFoundException("Can't find shader code at " + path);
        }

        var lines = File.ReadAllLines(path);
        Console.WriteLine("Try Read Shader: " + path);
        shaderCode = "";
        for (var i = 0; i < lines.Length; i++)
        {
            CheckShaderInclude(ref lines[i], path);

            shaderCode += lines[i] + '\n';
        }
        shaderCode = shaderCode.AsciiOnly();
        Console.WriteLine("Shader " + path + ": \n" + shaderCode);
        return true;
    }

    static void CheckShaderInclude(ref string line, string parentPath)
    {
        if (line.StartsWith(@"#include"))
        {
            // include 的子Shader所用的地址是相对于父级Shader的相对地址
            var path = Path.Combine(
                Path.GetDirectoryName(parentPath),
                line.CleanComment().Split("\"")[1].Trim()
            );
            Console.WriteLine("Try Include " + path);

            ReadShader(path, ref line);
        }
    }

    static string CleanComment(this string line)
    {
        return line.Trim().Split(@"\\").First();
    }

    public static string AsciiOnly(this string input, bool includeExtendedAscii = true)
    {
        int upperLimit = includeExtendedAscii ? 255 : 127;
        char[] asciiChars = input.Where(c => (int)c <= upperLimit).ToArray();
        return new string(asciiChars);
    }
}
